package com.example.cloud.consume.order.controller;

import com.example.cloud.consume.order.loadbalanced.LoadBalancer;
import com.example.cloud.entities.entity.Payment;
import com.example.cloud.entities.utils.SimpleMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * 订单控制器
 *
 * @author frank
 * @create 2020-11-26 16:19
 **/
@Api(tags = "订单模块")
@RestController
@RequestMapping("/order")
public class OrderController {

    public static final String PAYMENT_URL = "http://CLOUD-PROVIDER-PAYMENT";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;


    @ApiOperation("查询详情")
    @RequestMapping(value = "/consumer/payment/{id}" , method = RequestMethod.GET)
    public SimpleMessage<Payment> findOne(@PathVariable long id) {
        //return restTemplate.getForObject(PAYMENT_URL+"/payment/"+id,SimpleMessage.class);
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT");
        if(instances == null || instances.size() <= 0){
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/payment/"+id,SimpleMessage.class);
    }

    @ApiOperation("创建支付信息")
    @GetMapping("/consumer/payment/create")
    public SimpleMessage<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment",payment,SimpleMessage.class);
    }



}
